package com.wrk._3_方法._02_习题;

import java.util.Arrays;

public class _010_验证歌德巴赫2 {
    public static void main(String[] args) {
        int max = 20;
        //1、生成6～20之间的素数数组
        int [] primeNumberArray =primesArray(max);
        System.out.println("打印素数数组："+Arrays.toString(primeNumberArray));

        //2、生成6～20之间的偶数数组
        int [] evenArray = evenArray(max);
        System.out.println("打印偶数数组："+Arrays.toString(evenArray));

        //3、判断每一个偶数是否可分解为两个素数之和
        System.out.println("验证结果如下：");
        judge(primeNumberArray, evenArray);
    }

    /**求素数数组*/
    public static int [] primesArray(int max){
        //定义原始数组
        int [] generatingPrimes = new int[max];
        //1、找出所有2-20之间素数，输出为数组
            //求素数素组长度
        int count = 0;
        int count2 = 0;
        for (int number1 =2; number1 <= max; number1++){
            for (int number2 = 2;number2 <= number1; number2++){
                if (number1 % number2 == 0){
                    count++;
                }
            }
            //记录素数到原始数组中
            if (count ==1){
                generatingPrimes[count2++] = number1;
                count =0;
            }else {
                count = 0;
            }
        }
        //定义素数数组，将素数复制到数组中
        int [] primeNumberArray = Arrays.copyOf(generatingPrimes,count2);
        return  primeNumberArray;
    }
    /**求偶数数组*/
    public static int [] evenArray(int max){
        //求偶数数组长度
        int count1 = (max - 6)/2 + 1;
        //定义偶数数组
        int [] evenArrays = new int[count1];
        //给偶数数组赋值
        for (int i = 0; i < evenArrays.length; i++) {
            evenArrays[i] = 6 + 2 * i;
        }
        return evenArrays;
    }
    /**判断每一个偶数是否可分解为两个素数之和*/
    private static void judge(int[] primeNumberArray, int[] evenArray) {
        //遍历偶数数组
        for (int even : evenArray) {
            boolean foul = false;
            //遍历素数数组，求和是否相等
            for (int j = 0; j < primeNumberArray.length; j++) {
                for (int k = j; k < primeNumberArray.length; k++) {
                    if (primeNumberArray[j] + primeNumberArray[k] == even){
                        System.out.println(even+"="+ primeNumberArray[j]+"+"+ primeNumberArray[k]);
                        foul = true;
                        break;
                    }
                }
                //找到第一个合法解，已经验证了当前偶数 even 的哥德巴赫猜想成立，无需继续检查其他素数组合，跳出循环
                if (foul) break;
            }
        }
    }
}
